import React, { useState, useEffect } from'react';
import { Table, Button, Space, Pagination, Modal, notification } from 'antd';
import alist from './list.module.less';
import { getaccount,delallaccount, reviseaccount } from '../../../api/account';
// import { Dayjs } from 'dayjs';
// 导出一个名为Account的函数组件

export default function Account() {
// const day = new Dayjs();
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [dataSource, setDataSource] = useState([]);
  const [total, setTotal] = useState(0); // 用于存储数据总条数
  const [api, contextHolder] = notification.useNotification();
  const [confirmVisible, setConfirmVisible] = useState(false); // 控制确认框的显示与隐藏
  const [deleteId, setDeleteId] = useState(null); // 存储要删除的记录的id
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingRecord, setEditingRecord] = useState(null);
  const [formAccount, setFormAccount] = useState('');
  const [formUserGroup, setFormUserGroup] = useState('');
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10); // 新增，用于控制每页显示的条数

  const onSelectChange = (newSelectedRowKeys) => {
    console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const columns = [
    {
      title: '账号',
      dataIndex: 'account',
    },
    {
      title: '用户组',
      dataIndex: 'userGroup',
    },
    {
      title: '创建时间',
      dataIndex: 'ctime',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button type="primary" size='small' onClick={() => {
            setEditingRecord(record);
            setIsModalOpen(true);
            setFormAccount(record.account);
            setFormUserGroup(record.userGroup);
          }}>编辑</Button>
          <Button
            danger
            type="primary"
            size='small'
            onClick={() => {
              setDeleteId(record.id);
              setConfirmVisible(true);
            }}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const del = (id) => {
    delUser(id);
  };

  const openNotification = (title, description) => {
    api.info({
      message: title,
      description,
      placement: 'top',
    });
  };

  const showConfirm = () => {
    Modal.confirm({
      title: '确认删除',
      content: '你确定要删除这条记录吗？',
      okText: '确定',
      cancelText: '取消',
      onOk() {
        if (deleteId!== null) {
          del(deleteId);
        }
        setConfirmVisible(false);
      },
      onCancel() {
        setConfirmVisible(false);
      },
    });
  };

  // 获取数据
  const fetchUserData = async (currentPage, pageSize) => {
    try {
      const { data: responseData, total: responseTotal } = await getaccount({
        currentPage,
        pageSize,
      });
      const updatedData = responseData.map((item, index) => ({
       ...item,
        key: item.id ,
      }));
      setDataSource(updatedData);
      setTotal(responseTotal);
    } catch (error) {
      console.error('获取数据时出错:', error);
      openNotification('提示', '数据获取失败，请稍后再试');
    }
  };

  // 删除用户
  const delUser = async (id) => {
    try {
      const { msg, code } = await delallaccount({ id });
      console.log(msg);
      if (code === 0) {
        const newDataSource = dataSource.filter((item) => item.id!== id);
        setDataSource(newDataSource);
        openNotification('提示', msg);
        // 更新总条数
        setTotal(total - 1); 
      } else {
        openNotification('提示', '删除失败，请稍后再试');
      }
    } catch (error) {
      console.error('删除用户时出错:', error);
      openNotification('提示', '删除失败，请稍后再试');
    }
  };

  // 修改账号
  const handleEditOk = async () => {
    if (editingRecord) {
      const updateData = {
        id: editingRecord.id,
        account: formAccount,
        userGroup: formUserGroup
      };
      try {
        const { msg, code } = await reviseaccount(updateData);
        if (code === 0) {
          const newDataSource = dataSource.map((item) =>
            item.id === editingRecord.id? updateData : item
          );
          setDataSource(newDataSource);
          // 重新构造包含分页信息的参数对象
          const data = {
            currentPage: page,
            pageSize: pageSize,
          };
          fetchUserData(data.currentPage, data.pageSize);
          openNotification('提示', msg);
        } else {
          openNotification('提示', '修改失败，请稍后再试');
        }
      } catch (error) {
        console.error('修改用户时出错:', error);
        openNotification('提示', '修改失败，请稍后再试');
      }
    }
    setIsModalOpen(false);
  };

  useEffect(() => {
    fetchUserData(page, pageSize);
  }, [page, pageSize]);

  useEffect(() => {
    if (confirmVisible) {
      showConfirm();
    }
  }, [confirmVisible]);

  return (
    <div>
      {contextHolder}
      <div className={alist.title}>
        账户列表
      </div>
      <div style={{ height: '550px', overflow: 'auto' }}>
        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={dataSource}
          pagination={false}
        />
      </div>
      <Pagination
        className={alist.page}
        total={total}
        showSizeChanger
        showQuickJumper
        showTotal={(total) => `总共 ${total} 条`}
        current={page}
        pageSize={pageSize}
        onChange={(pageNumber) => {
          setPage(pageNumber);
          const data = {
            currentPage: pageNumber,
            pageSize: pageSize,
          };
          fetchUserData(data.currentPage, data.pageSize);
        }}
        onShowSizeChange={(current, size) => {
          setPage(1);
          setPageSize(size);
          const data = {
            currentPage: 1,
            pageSize: size,
          };
          fetchUserData(data.currentPage, data.pageSize);
        }}
      />
      {/* 编辑框 */}
      <Modal
        title="修改账号信息"
        open={isModalOpen}
        onOk={handleEditOk}
        onCancel={() => setIsModalOpen(false)}
      >
        <div>
          <label>账号名</label>
          <input
            type="text"
            value={formAccount}
            onChange={(e) => setFormAccount(e.target.value)}
          />
        </div>
        <div>
          <label>用户组</label>
          <select
            value={formUserGroup}
            onChange={(e) => setFormUserGroup(e.target.value)}
          >
            <option value="普通用户">普通用户</option>
            <option value="超级管理员">超级管理员</option>
          </select>
        </div>
      </Modal>
    </div>
  );
}